package com.wlcb.jpower.chat.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wlcb.jpower.chat.api.BaiduIdentifyApi;
import com.wlcb.jpower.chat.api.BaiduUnitApi;
import com.wlcb.jpower.chat.pojo.baidu.UnitChatRequest;
import com.wlcb.jpower.chat.pojo.baidu.UnitChatRequest.Request;
import com.wlcb.jpower.chat.pojo.baidu.UnitChatResponse;
import com.wlcb.jpower.chat.service.BaiduUnitService;
import com.wlcb.jpower.constant.RedisEunm;
import com.wlcb.jpower.module.common.redis.RedisUtil;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.RandomUtil;
import com.wlcb.jpower.properties.JpowerChatBaiduUnitProperties;
import com.wlcb.jpower.utils.RedisHelpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/3/31 11:58
 * @desc:
 */
@Slf4j
@Service("baiduUnitServiceImpl")
public class BaiduUnitServiceImpl implements BaiduUnitService {
    @Resource
    private BaiduIdentifyApi baiduIdentifyApi;
    @Resource
    private BaiduUnitApi baiduUnitApi;
    @Autowired
    private JpowerChatBaiduUnitProperties unitProperties;

    @Override
    public String accesstoken() {
        RedisUtil redisUtil = RedisHelpUtils.getRedisUtil();
        Object obj = redisUtil.get(RedisEunm.BAIDU_ACCESSTOKEN.getKeyPrefix() + unitProperties.getAppKey());
        if (!Fc.isNull(obj)) {
            return obj.toString();
        }
        Map<String, String> result = baiduIdentifyApi.accesstoken(unitProperties.getAppKey(), unitProperties.getSecretKey());
        String accessToken = result.get("access_token");
        if (Fc.isBlank(accessToken)) {
            log.error("baidu unit accesstoken fail");
            return null;
        }
        redisUtil.set(RedisEunm.BAIDU_ACCESSTOKEN.getKeyPrefix() + unitProperties.getAppKey(), accessToken,
                Long.valueOf(result.get("expires_in")), TimeUnit.SECONDS);
        log.warn("baidu accesstoken :{}", accessToken);
        return accessToken;
    }

    @Override
    public String say(String query, String userId) {
        RedisUtil redisUtil = RedisHelpUtils.getRedisUtil();
        Object object = redisUtil.get(RedisEunm.BAIDU_UNIT_SESSION.getKeyPrefix() + userId);
        if (Fc.isNull(object)) {
            redisUtil.set(RedisEunm.BAIDU_UNIT_SESSION.getKeyPrefix() + userId, "", RedisEunm.BAIDU_UNIT_SESSION.getTime(), RedisEunm.BAIDU_UNIT_SESSION.getTimeUnit());
            object = "";
        }

        UnitChatRequest unitChatRequest = new UnitChatRequest();
        unitChatRequest.setServiceId(unitProperties.getServiceId());
        unitChatRequest.setLogId(RandomUtil.random6Num());
        unitChatRequest.setSessionId(Fc.isBlank(object.toString()) ? "" : object.toString());
        Request request = new Request();
        request.setQuery(query);
        request.setUserId(userId);
        unitChatRequest.setRequest(request);

        String resultStr = baiduUnitApi.query(accesstoken(), unitChatRequest);

        UnitChatResponse unitChatResponse = JSONObject.parseObject(resultStr, UnitChatResponse.class);
        log.error("unit reply result:{}", unitChatResponse.toString());
        if ("292003".equals(unitChatResponse.getErrorCode())) {
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("isReply", true);
            jsonObject.put("type", "text");
            jsonObject.put("content", "公众号较忙，请稍后再试！");
            jsonArray.add(jsonObject);
            return jsonArray.toJSONString();
        }
        if (!"0".equals(unitChatResponse.getErrorCode())) {
            return "";
        }
        if (Fc.isBlank(object.toString())) {
            RedisHelpUtils.getRedisUtil().set(RedisEunm.BAIDU_UNIT_SESSION.getKeyPrefix() + userId, unitChatResponse.getResult().getSessionId(), RedisEunm.BAIDU_UNIT_SESSION.getTime(), RedisEunm.BAIDU_UNIT_SESSION.getTimeUnit());
        }
        List<UnitChatResponse.Response> responseList = unitChatResponse.getResult().getResponseList();
        for (UnitChatResponse.Response response : responseList) {
            List<UnitChatResponse.Action> actionList = response.getActionList();
            for (UnitChatResponse.Action action : actionList) {
                return action.getSay();
            }
        }
        return "";
    }
}
